﻿using System;
using System.IO;
using EnvDTE80;
using EnvDTE;

namespace Yama.TemplateWizard
{
    public class LibsWizard : ProjectWizard
    {

        public override void ProjectFinishedGenerating(Project project)
        {
            MoveLibsToTheirFolder();
        }

        private static void MoveLibsToTheirFolder()
        {
            string originalLocation = GetSolutionRootPath() + SolutionName + "\\LibsContainer\\Libs";

            if (Directory.Exists(originalLocation))
            {
                string targetLibFolder = GetSolutionRootPath() + SolutionName + "\\libs";

                Directory.Move(originalLocation, targetLibFolder);

                Solution2 solution = Dte.Solution as Solution2;

                if (solution == null)
                    throw new Exception("Cannot cast Solution");

                RemoveLibsProjectFromSolution(solution);
                // Give the solution time to release the lock on the project file
                System.Threading.Thread.Sleep(500);

                Directory.Delete(GetSolutionRootPath() + SolutionName + "\\LibsContainer", true);
            }
            else
            {
                throw new ApplicationException("Couldn't find " + originalLocation + " to move");
            }
        }

        private static string GetSolutionFileName()
        {
            return SolutionName + ".sln";
        }

        private static string GetSolutionFileFullName()
        {
            return Dte.Solution.Properties.Item("Path").Value.ToString();
        }

        private static string GetSolutionRootPath()
        {
            return GetSolutionFileFullName().Replace(GetSolutionFileName(), "");
        }

        private static void RemoveLibsProjectFromSolution(Solution2 solution)
        {
            foreach (Project project in solution.Projects)
            {
                if (project.Name != "LibsContainer") continue;

                solution.Remove(project);
                break;
            }
        }
    }
}
